import fs from 'fs-extra'
import * as path from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

export class ResourceManager {
  private assetsPath: string
  private toolsPath: string
  private scriptPath: string

  constructor() {
    // 检查是否在构建后的环境中运行
    const isBuilt = __filename.includes('dist')

    if (isBuilt) {
      // 构建后的路径
      const distDir = path.dirname(__dirname)
      this.assetsPath = path.join(distDir, 'pm', 'assets')
      this.toolsPath = path.join(distDir, 'pm', 'tools')
      this.scriptPath = path.join(distDir, 'pm', 'tools', 'script')
    } else {
      // 开发环境路径
      this.assetsPath = path.join(__dirname, 'assets')
      this.toolsPath = path.join(__dirname, 'tools')
      this.scriptPath = path.join(__dirname, 'tools', 'script')
    }
  }

  /**
   * 复制资源文件和脚本文件到用户指定目录
   * @param targetPath 用户指定的目标目录路径
   */
  async copyAssetsToTarget(targetPath: string): Promise<void> {
    try {
      // 确保目标目录存在
      await fs.ensureDir(targetPath)

      // 创建 assets 子目录并复制资源文件
      const assetsTargetPath = path.join(targetPath, 'assets')
      await fs.ensureDir(assetsTargetPath)
      await fs.copy(this.assetsPath, assetsTargetPath, {
        overwrite: true
      })
      console.log(`静态资源文件已成功复制到: ${assetsTargetPath}`)

      // 创建 script 子目录并复制脚本文件
      const scriptTargetPath = path.join(targetPath, 'script')
      await fs.ensureDir(scriptTargetPath)
      await fs.copy(this.scriptPath, scriptTargetPath, {
        overwrite: true
      })
      console.log(`启动脚本文件已成功复制到: ${scriptTargetPath}`)

    } catch (error) {
      throw new Error(`复制资源文件失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  /**
   * 获取提示词内容
   * @param promptPath 提示词文件的相对路径
   */
  async getPromptContent(promptPath: string): Promise<string> {
    try {
      const fullPath = path.join(this.toolsPath, 'prompts', promptPath)
      
      if (!await fs.pathExists(fullPath)) {
        throw new Error(`提示词文件不存在: ${promptPath}`)
      }
      
      const content = await fs.readFile(fullPath, 'utf-8')
      return content
    } catch (error) {
      throw new Error(`读取提示词文件失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  /**
   * 获取模板内容
   * @param templatePath 模板文件的相对路径
   */
  async getTemplateContent(templatePath: string): Promise<string> {
    try {
      const fullPath = path.join(this.toolsPath, 'framework', templatePath)
      
      if (!await fs.pathExists(fullPath)) {
        throw new Error(`模板文件不存在: ${templatePath}`)
      }
      
      const content = await fs.readFile(fullPath, 'utf-8')
      return content
    } catch (error) {
      throw new Error(`读取模板文件失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  /**
   * 列出所有可用的提示词文件
   */
  async listPrompts(): Promise<string[]> {
    try {
      const promptsPath = path.join(this.toolsPath, 'prompts')
      const files = await this.getFilesRecursively(promptsPath, '.md')
      return files.map(file => path.relative(promptsPath, file))
    } catch (error) {
      throw new Error(`列出提示词文件失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  /**
   * 列出所有可用的模板文件
   */
  async listTemplates(): Promise<string[]> {
    try {
      const templatesPath = path.join(this.toolsPath, 'framework')
      const files = await this.getFilesRecursively(templatesPath, '.html')
      return files.map(file => path.relative(templatesPath, file))
    } catch (error) {
      throw new Error(`列出模板文件失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  /**
   * 递归获取指定目录下的所有文件
   */
  private async getFilesRecursively(dir: string, extension: string): Promise<string[]> {
    const files: string[] = []
    
    if (!await fs.pathExists(dir)) {
      return files
    }
    
    const items = await fs.readdir(dir)
    
    for (const item of items) {
      const fullPath = path.join(dir, item)
      const stat = await fs.stat(fullPath)
      
      if (stat.isDirectory()) {
        const subFiles = await this.getFilesRecursively(fullPath, extension)
        files.push(...subFiles)
      } else if (path.extname(item) === extension) {
        files.push(fullPath)
      }
    }
    
    return files
  }

  /**
   * 检查资源文件是否存在
   */
  async checkAssetsExist(): Promise<boolean> {
    return await fs.pathExists(this.assetsPath)
  }

  /**
   * 检查工具目录是否存在
   */
  async checkToolsExist(): Promise<boolean> {
    return await fs.pathExists(this.toolsPath)
  }

  /**
   * 检查脚本目录是否存在
   */
  async checkScriptExist(): Promise<boolean> {
    return await fs.pathExists(this.scriptPath)
  }
}
